TemplateGen = class()

function TemplateGen:init(world)
    self.world = world
end

function TemplateGen:genTemplate(count,template)
    local l,w,h = self.world.length,self.world.width,self.world.height - 1
    template:setBound(self.world)
    local i = 1
    while i <= count do
        local x,y,z = template:getGenCoord()
        local tr = template:getTemplate(math.random(1,template.count))
        x = x - #tr // 2
        z = z - #tr[1][1] // 2
        for xa = 1, #tr do
            for ya = 1, #tr[1] do
                for za = 1, #tr[1][1] do
                    local xb,yb,zb = xa - 1,ya - 1,za - 1
                    if x + xb < self.world.x0 or y + yb < 0 or z + zb < self.world.z0 or x + xb > self.world.x1 or y + yb > self.world.height - 1 or z + zb > self.world.z1 then
                        
                    elseif template:canReplace(self.world:getBlock(x + xb,y + yb,z + zb)) then
                        local tile = tr[xa][ya][za]
                        if type(tile) == "table" then
                            if math.random() <= tile[2] then
                                self.world:setBlockDirectly(x + xb,y + yb,z + zb,tile[1])
                            end
                        else
                            self.world:setBlockDirectly(x + xb,y + yb,z + zb,tile)
                        end
                    end
                end
            end
        end
        i = i + 1
    end
    return self
end

function TemplateGen:genPlant(count,plantid)
    local l,w,h = self.world.length,self.world.width,self.world.height - 1
    for i = 1,count do
        local x = math.random(self.world.x0 + 1,self.world.x1 - 1)
        local z = math.random(self.world.z0 + 1,self.world.z1 - 1)
        local y = h
        while self.world:getBlock(x,y,z) == Block.air.id do
            y = y - 1
        end
        if self.world:getBlock(x,y,z) == Block.soil.id or self.world:getBlock(x,y,z) == Block.grass.id then
            self.world:setBlockDirectly(x,y + 1,z,plantid)
        end
    end
    return self
end